package com.project.server.interceptor;

import com.project.server.common.api.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.server.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {


    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 排除登录和注册接口
        if (request.getRequestURI().equals("/api/auth/login") ||
            request.getRequestURI().equals("/api/auth/register")) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.hasText(token) && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 如果没有token，返回未认证错误
        if (!StringUtils.hasText(token)) {
            handleError(response, 401, "未认证");
            return false;
        }

        // 验证token
        if (!JwtUtil.validateToken(token)) {
            handleError(response, 401, "token已过期或无效");
            return false;
        }

        // token验证通过，可以在这里将用户信息存入request
        request.setAttribute("username", JwtUtil.parseJWT(token));
        return true;
    }

    private void handleError(HttpServletResponse response, int code, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        response.getWriter().write(objectMapper.writeValueAsString(Result.error(code, message)));
    }
}
